import os
import uuid
import pyttsx3
from config.ChatTTS_config import chat_tts_config
from models.ChatTTS_model import ChatTTSAudioFile, AudioFileListResponse
from entity.schema.ChatTTS_schema import ChatTTSRequest
from utils.logger import logger
from datetime import datetime

class ChatTTSService:
    def __init__(self):
        self.engine = self._init_engine()
        logger.info("ChatTTS 服务初始化完成")

    def _init_engine(self):
        """初始化语音引擎"""
        try:
            engine = pyttsx3.init()
            return engine
        except Exception as e:
            logger.error(f"语音引擎初始化失败: {str(e)}")
            raise Exception("语音引擎初始化失败")

    def _select_voice(self, voice_preference: str):
        """选择语音"""
        def find_voice(keywords):
            for voice in self.engine.getProperty('voices'):
                voice_info = f"{voice.id.lower()} {voice.name.lower()}"
                if all(keyword in voice_info for keyword in keywords):
                    self.engine.setProperty('voice', voice.id)
                    return voice.id
            return None

        if voice_preference != "auto":
            voice_id = find_voice([voice_preference.lower()])
            if voice_id:
                return voice_id
            logger.warning(f"未找到指定语音: {voice_preference}, 使用默认语音")
        else:
            voice_id = find_voice(["chinese", "zh"])
            if voice_id:
                return voice_id
            logger.warning("未找到中文语音, 使用默认语音")
        return None

    def generate_speech(self, request: ChatTTSRequest) -> ChatTTSAudioFile:
        """生成语音文件"""
        try:
            # 设置语音
            voice_id = self._select_voice(request.voice)
            # 设置语速和音量
            self.engine.setProperty('rate', max(50, min(300, request.speed)))
            self.engine.setProperty('volume', max(0.0, min(1.0, request.volume)))
            # 生成唯一文件名
            filename = f"chat_tts_{uuid.uuid4().hex}.wav"
            filepath = os.path.join(chat_tts_config.AUDIO_CACHE_DIR, filename)
            self.engine.save_to_file(request.text, filepath)
            self.engine.runAndWait()
            file_size = os.path.getsize(filepath)

            return ChatTTSAudioFile(
                filename=filename,
                text=request.text,
                voice=voice_id or "default",
                speed=request.speed,
                volume=request.volume,
                created_at=datetime.now(),
                file_size=file_size,
                file_path=filepath
            )
        except Exception as e:
            logger.error(f"语音生成失败: {str(e)}")
            raise Exception("语音生成失败")

    # 新增获取音频文件列表方法
    def get_audio_files(self) -> AudioFileListResponse:
        files = []
        for root, dirs, files_in_dir in os.walk(chat_tts_config.AUDIO_CACHE_DIR):
            for file in files_in_dir:
                file_path = os.path.join(root, file)
                file_size = os.path.getsize(file_path)
                created_at = datetime.fromtimestamp(os.path.getctime(file_path))
                # 这里由于没有存储 text、voice、speed、volume 信息，暂时留空
                audio_file = ChatTTSAudioFile(
                    filename=file,
                    text="",
                    voice="",
                    speed=0,
                    volume=0.0,
                    created_at=created_at,
                    file_size=file_size,
                    file_path=file_path
                )
                files.append(audio_file)
        return AudioFileListResponse(files=files)

    # 新增清理旧文件方法
    def clean_old_audio_files(self):
        return chat_tts_config.clean_old_files()